package rest_template;


import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import rest_template.pojo.User;

import java.util.HashMap;
import java.util.Map;

@Controller
public class EmitController {

    private static final String HOST = "http://192.168.2.105:8081/";

    /* get示例 */
    @GetMapping("gfe1")
    @ResponseBody
    public String gfe1() {
        ResponseEntity<String> entity = new RestTemplate().getForEntity(HOST + "gfe1r", String.class);
        return "gfe1:" + entity.getBody();
    }

    @GetMapping("gfe2")
    @ResponseBody
    public String gfe2() {
        String url = HOST + "gfe1r?name={1}";
        ResponseEntity<String> entity = new RestTemplate().getForEntity(url, String.class, "akali");
        return "gfe2:" + entity.getBody();
    }

    @GetMapping("gfe3")
    @ResponseBody
    public String gfe3() {
        String url = HOST + "gfe1r?name={name}&pass={pass}";
        Map<String, String> map = new HashMap<>();
        map.put("name", "akali");
        map.put("pass", "root");
        ResponseEntity<String> entity = new RestTemplate().getForEntity(url, String.class, map);
        return "gfe3:" + entity.getBody();
        //上面两行等效于getForObject[getForEntity将结果封装成了ResponseEntity<T>返回并且可以获取请求头等信息|getForObject将结果T直接返回]
        //return new RestTemplate().getForObject(url, String.class, map);
    }


    /* post示例 */
    @GetMapping("pfe1")
    @ResponseBody
    public String pfe1() {
        String url = HOST + "pfe1r";
        Map<String, String> map = new HashMap();
        map.put("name", "akali");
        map.put("pass", "root");
        ResponseEntity<String> entity = new RestTemplate().postForEntity(url, map, String.class);
        return "pfe1:" + entity.getBody();
    }

    @GetMapping("pfe2")
    @ResponseBody
    public String pfe2() {
        String url = HOST + "pfe1r";
        User user = new User("akali", "root");
        ResponseEntity<String> entity = new RestTemplate().postForEntity(url, user, String.class);
        return "pfe2:" + entity.getBody();
    }

}
